package com.docker.core.mvc.service;

import com.docker.core.constant.MainConstant;
import com.docker.core.third.docker.DockerKit;
import com.docker.core.third.docker.SelfDockerClient;
import com.docker.login.LoginRedis;
import com.docker.sys.app.AppBean;
import com.docker.sys.app.AppRedis;
import com.docker.sys.user.UserBean;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.upload.UploadFile;
import kit.docker.datetime.DateKit;
import kit.docker.exception.BaseException;
import kit.docker.exception.UploadException;
import kit.docker.math.RandomKit;
import kit.docker.validator.ValidatorKit;
import kit.docker.web.APIResCode;
import com.docker.core.third.websocket.WebsocketKit;
import org.apache.log4j.Logger;

import javax.websocket.Session;
import java.sql.Connection;

public class BaseService {

    private static final Logger logger = Logger.getLogger(BaseService.class);

    // =====================日志输出=======================================
    protected void logInfo(String msg) {
        logger.info(msg);
    }

    protected void logError(String msg) {
        logger.error(msg);
    }

    protected void logInfo(String msg, Throwable e) {
        logger.info(msg, e);
    }

    protected void logError(String msg, Throwable e) {
        logger.error(msg, e);
    }

    // =====================异常拦截处理=======================================
    protected void throwError(Integer status) {
        throw new BaseException(status);
    }

    protected void throwError(String message) {
        throw new BaseException(message);
    }

    protected void throwError(Integer status, String message) {
        throw new BaseException(status, message);
    }

    protected void throwError(Object data, Integer status, String message) {
        throw new BaseException(data, status, message);
    }

    protected void throwUploadError(UploadFile file, String message) {
        throw new UploadException(file, message);
    }

    // =====================常用参数获取==============================================

    //事务隔离级别
    //TRANSACTION_NONE  不使用事务。
    //TRANSACTION_READ_UNCOMMITTED  允许脏读。
    //TRANSACTION_READ_COMMITTED  防止脏读，最常用的隔离级别,并且是大多数数据库的默认隔离级别
    //TRANSACTION_REPEATABLE_READ  可以防止脏读和不可重复读，
    //TRANSACTION_SERIALIZABLE  可以防止脏读，不可重复读取和幻读，（事务串行化）会降低数据库的效率
    protected boolean tx(IAtom atom) {
        return Db.use(MainConstant.DB_DOCKER).tx(Connection.TRANSACTION_READ_COMMITTED, atom);
    }

    protected String getNowDateTime() {
        return DateKit.getNowDateTime();
    }

    protected String getToday() {
        return DateKit.getToday();
    }

    protected String getUUID32() {
        return RandomKit.getUUID();
    }

    protected AppBean getApp(String appId) {
        return AppRedis.getApp(appId);
    }

    protected UserBean getUser(String appId, String token) {
        UserBean user = LoginRedis.getSessionUser(appId, token, UserBean.class);
        if (!StrKit.notNull(user)) {
            throwError(APIResCode.SESSION_TIME_OUT);
        }
        return user;
    }

    protected String getUserId(String appId, String token) {
        return getUser(appId, token).getUser_id();
    }

    protected boolean isSuperAdmin(String appId, String token) {
        return isSuperAdmin(getUser(appId, token));
    }

    protected boolean isSuperAdmin(UserBean userBean) {
        return "1".equals(userBean.getIs_admin());
    }

    protected String getClientKey(String token, String serverId) {
        if (!ValidatorKit.validateUUID32(token, false)) {
            throwError("用户登录状态错误");
        }
        if (!ValidatorKit.validateUUID32(serverId, false)) {
            throwError("docker服务标识错误");
        }
        //TODO 校验真实登录状态
        return DockerKit.key(token, serverId);
    }

    protected SelfDockerClient getDockerClient(String clientKey) {
        return DockerKit.getSeflClient(clientKey);
    }

    protected void refreshLCTime(String token, String serverId) {
        refreshLCTimeKey(getClientKey(token, serverId));
    }

    protected void refreshLCTimeKey(String clientKey) {
        DockerKit.refreshLCTime(clientKey);
    }

    protected void refreshLCTimeKey(SelfDockerClient dockerClient) {
        DockerKit.refreshLCTime(dockerClient);
    }

    protected void sendMsg(String connectKey, Object data) {
        WebsocketKit.sendMsg(connectKey, data);
    }

    protected void sendMsg(String connectKey, String cmd, Object data) {
        WebsocketKit.sendMsg(connectKey, cmd, data);
    }

    protected void sendMsg(Session session, Object data) {
        WebsocketKit.sendMsg(session, null, data);
    }

    protected void sendMsg(Session session, String cmd, Object data) {
        WebsocketKit.sendMsg(session, cmd, data);
    }

}
